package com.red.net {
	import flash.events.*;
	import flash.utils.*;
	import flash.net.Socket;		

	/**
	 * @author zhangs
	 */
	public class SocketConnection implements IEventDispatcher {
		private var socket : Socket;
		private var dispatcher : EventDispatcher;
		
		public function SocketConnection(server : String = "127.0.0.1", port : uint = 8000) {
			socket = new Socket();
	        socket.addEventListener(Event.CLOSE, closeHandler);
	        socket.addEventListener(Event.CONNECT, connectHandler);
	        socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
	        socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			socket.addEventListener(ProgressEvent.SOCKET_DATA, receiveData);
			
			dispatcher = new EventDispatcher(this);

			socket.connect(server, port);
		}

		public function sendData(data : Object):void {
			var ba : ByteArray = new ByteArray();
			ba.writeMultiByte(data.toString(), "UTF-8");
			socket.writeBytes(ba);
			socket.flush();
		}
		
		private function receiveData(e : ProgressEvent) : void{
			var ba : ByteArray = new ByteArray();
			socket.readBytes(ba);
			
			var event : SocketEvent = new SocketEvent();
			event.data = ba.toString();
			dispatchEvent(event);
		}

		public function dispatchEvent(event : Event) : Boolean {
			return dispatcher.dispatchEvent(event);
		}
		
		public function hasEventListener(type : String) : Boolean {
			return dispatcher.hasEventListener(type);
		}
		
		public function willTrigger(type : String) : Boolean {
			return dispatcher.willTrigger(type);
		}
		
		public function removeEventListener(type : String, listener : Function, useCapture : Boolean = false) : void {
			dispatcher.removeEventListener(type, listener, useCapture);
		}

		public function addEventListener(type : String, listener : Function, useCapture : Boolean = false, priority : int = 0, useWeakReference : Boolean = false) : void {
			dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference);
		}

	    private function closeHandler(event:Event):void {
	        trace("closeHandler: " + event);
			dispatcher.dispatchEvent(event);
		}
	
	    private function connectHandler(event:Event):void {
	        trace("connectHandler: " + event);
	        dispatcher.dispatchEvent(event);
	    }
	
	    private function ioErrorHandler(event:IOErrorEvent):void {
	        trace("ioErrorHandler: " + event);
	        dispatcher.dispatchEvent(event);
	    }
	
	    private function securityErrorHandler(event:SecurityErrorEvent):void {
	        trace("securityErrorHandler: " + event);
	        dispatcher.dispatchEvent(event);
	    }
	}
}
